"use client"

import { useEffect, useState, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import throttle from 'lodash/throttle';

// 定义彩色数组
const colors = [
  'rgba(230, 126, 34, ',
  'rgba(54, 162, 235, ',
  'rgba(255, 205, 86, ',
  'rgba(75, 192, 192, ',
  'rgba(153, 102, 255, ',
  'rgba(255, 159, 64, '
];

// 生成气泡的样式
const generateBubbleStyle = (size, color) => {
  return {
    position: 'absolute',
    width: `${size}px`,
    height: `${size}px`,
    background: `${color}1)`, // 固定透明度为 1
    borderRadius: '50%',
    boxShadow: `0 0 10px ${color}1)` // 固定透明度为 1
  };
};

// 用于生成唯一 key 的计数器
let keyCounter = 0;

export function MouseFollower() {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [trail, setTrail] = useState([]);
  const throttleRef = useRef(null);
  const [initialColor, setInitialColor] = useState(null);

  useEffect(() => {
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    setInitialColor(randomColor);
  }, []);

  useEffect(() => {
    const handleMouseMove = throttle((e) => {
      setMousePosition({ x: e.clientX, y: e.clientY });

      const randomColor = colors[Math.floor(Math.random() * colors.length)];
      const newDot = {
        // 使用计数器生成唯一的 key
        id: keyCounter++,
        x: e.clientX,
        y: e.clientY,
        color: randomColor
      };

      // 减少保留的气泡数量，这里改为只保留最近的 8 个气泡
      setTrail((prevTrail) => [...prevTrail, newDot].slice(-8));
    }, 16); // 大约 60 FPS

    throttleRef.current = handleMouseMove;

    window.addEventListener('mousemove', handleMouseMove);

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
    };
  }, []);

  useEffect(() => {
    if (trail.length > 0) {
      // 减少时间间隔，让气泡消失更快，这里设置为 80 毫秒
      const timer = setTimeout(() => {
        setTrail((prevTrail) => prevTrail.slice(1));
      }, 80);

      return () => clearTimeout(timer);
    }
  }, [trail]);

  return (
    <div className="fixed inset-0 pointer-events-none overflow-hidden" style={{ zIndex: 9999 }}>
      {/* 主光标 */}
      <AnimatePresence>
        {initialColor && <motion.div
          className="absolute"
          style={{
            left: mousePosition.x - 10,
            top: mousePosition.y - 10,
            ...generateBubbleStyle(20, initialColor)
          }}
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          exit={{ scale: 0 }}
          transition={{
            duration: 0.2,
            ease: "easeOut" // 使用更平滑的过渡曲线
          }}
        />}
      </AnimatePresence>

      {/* 轨迹点 */}
      <AnimatePresence>
        {trail.map((dot, index) => (
          <motion.div
            key={dot.id}
            className="absolute"
            style={{
              left: dot.x,
              top: dot.y,
              marginLeft: `-${(12 - index * 0.7) / 2}px`,
              marginTop: `-${(12 - index * 0.7) / 2}px`,
              ...generateBubbleStyle(12 - index * 0.7, dot.color)
            }}
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            exit={{ scale: 0 }}
            transition={{
              duration: 0.2,
              ease: "easeOut" // 使用更平滑的过渡曲线
            }}
          />
        ))}
      </AnimatePresence>
    </div>
  );
}